//用户的store
import {defineStore} from "pinia";
import {logout, reqLogin, reqUserInfo} from "@/api/user";
import type {loginFormData, loginResponseData, userResponseData} from "@/api/user/type.ts";
import type {UserState} from '../types/types.ts'
import {GET_TOKEN, REMOVE_TOKEN, SET_TOKEN} from '@/utils/token.ts'
// 引入路由（常量路由）
import {anyRoute, constantRoutes,asyncRoute} from "@/router/routes.ts";
import router from "@/router/router.ts";
//引入深拷贝方法
//@ts-ignore
import cloneDeep from 'lodash/cloneDeep'

const useUserStore = defineStore('User',{
    //小仓库存储数据的地方
    state:():UserState=>{
        return {
            token: GET_TOKEN(),
            menuRoutes:constantRoutes,//仓库存储生成菜单需要数组（路由）
            username:'',
            avatar:'',
            buttons:[]
        }
    },
    //异步|逻辑的地方
    actions:{
        /**
         * 登录
         * @param data
         */
        async userLogin(data:loginFormData){
            // console.log(data)
            const res:loginResponseData = await reqLogin(data)
            // console.log(res)
            if(res.code==200){
                this.token=(res.data as string)
                SET_TOKEN((res.data as string))
                return 'ok'
            }else{
                return Promise.reject(new Error(res.data))
            }
        },
        /**
         * 获取用户信息
         */
        async userInfo() {
            const res: userResponseData = await reqUserInfo()
            // console.log(res)
            if (res.code === 200) {
                this.username = res.data.name
                this.avatar = res.data.avatar
                this.buttons = res.data.buttons
                const userAsyncRoute =filterAsyncRoute(cloneDeep(asyncRoute),res.data.routes)
                this.menuRoutes=[...userAsyncRoute,...constantRoutes,anyRoute];
                [...userAsyncRoute,anyRoute].forEach((route:any)=>{
                    router.addRoute(route)
                })
                // console.log(router.getRoutes())
                return 'ok'
            }else {
                return Promise.reject(res.message)
            }
        },
        /**
         * 退出登录
         */
         async userLogout(){
            const res:any = await logout()
            if(res.code==200){
                this.token=''
                this.username=''
                this.avatar=''
                REMOVE_TOKEN()
                return 'ok'
            }else{
                return Promise.reject(new Error(res.message))
            }
        }
    },
    //
    getters:{

    }
})
const filterAsyncRoute =(anyRoute:any,routes:any):any=>{
    return  anyRoute.filter((item:any)=>{
        if(routes.includes(item.name)){
            if(item.children&&item.children.length>0){
                item.children = filterAsyncRoute(item.children,routes)
            }
            return true
        }
    })
}
export default useUserStore